package lumingweihua.future.cn.baselibgxh.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonElement;

import java.util.ArrayList;
import java.util.List;

import lumingweihua.future.cn.baselibgxh.R;
import lumingweihua.future.cn.baselibgxh.adapter.BaseViewHolder;
import lumingweihua.future.cn.baselibgxh.adapter.CommonAdapter;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialog;
import lumingweihua.future.cn.baselibgxh.dialog.YesOrNoDialogEntity;
import lumingweihua.future.cn.baselibgxh.domain.GiftData;
import lumingweihua.future.cn.baselibgxh.domain.GiftDataAll;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.ImageUtils;
import lumingweihua.future.cn.baselibgxh.utils.MD5;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;

/**
 * Created by Administrator on 2018/9/22.
 */

public class GiftFragment extends Fragment implements View.OnClickListener,AbstractRequest.ApiCallBack {

    View rootView;
    View common_error_page_progressBar;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView  = inflater.inflate(R.layout.fragment_gift, container, false);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        rootView.findViewById(R.id.view_mask).setOnClickListener(this);
        rootView.findViewById(R.id.tv_cancel).setOnClickListener(this);
        rootView.findViewById(R.id.tv_charge).setOnClickListener(this);
        common_error_page_progressBar = rootView.findViewById(R.id.common_error_page_progressBar);
        initData(savedInstanceState);
    }

    private String anchor_id;
    private GiftChangeListener giftChangeListener;

    public void setListener(String anchor_id,GiftChangeListener giftChangeListener){
        this.anchor_id =anchor_id;
        this.giftChangeListener = giftChangeListener;
    }

    protected void initData(Bundle savedInstanceState) {
        requestGoodsLiwus();
    }

    private final int REQUEST_LIWUS = 8;
    private final int REQUEST_DASANG = 10;

    private void requestGoodsLiwus() {
        // TODO Auto-generated method stub
        common_error_page_progressBar.setVisibility(View.VISIBLE);
        BeanRequest<GiftDataAll, MamaHaoServerError> req = new BeanRequest<>(
                getContext(),
                "/api/present",
                this,
                GiftDataAll.class);

        req.setParam("token", SharedPreference.getString(getContext(),"token"));

        req.setTag(new ReqTag.Builder().build(REQUEST_LIWUS));
        FutureApi.getInstance().add(req);
    }

    private String id;
    /**
     * 打赏
     */
    private void requestDashang(String id) {
        this.id = id;
        common_error_page_progressBar.setVisibility(View.VISIBLE);
        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                getContext(), "/api/user/reward_user", this);

        req.setParam("present_id", id);
        req.setParam("token", SharedPreference.getString(getContext(),"token"));
        req.setParam("anchor_id", anchor_id);

        String key = "9b4aaf?&&##664bdef@c3fc3efa9";

        String time = System.currentTimeMillis()/1000 +"";
        req.setParam("sign", MD5.Md5(id+time+key).toLowerCase());

        req.setTag(new ReqTag.Builder().build(REQUEST_DASANG));
        FutureApi.getInstance().add(req);
    }


    private List<GiftData> giftDatas;
    private int cost;

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.view_mask || v.getId() == R.id.tv_cancel){
            giftChangeListener.onDissmiss();
        }else if(v.getId() == R.id.tv_charge){
            MyApplication.getInstance().gotoCharge();
        }
    }

    @Override
    public void onApiOnSuccess(ReqTag tag, Object data) {

        common_error_page_progressBar.setVisibility(View.GONE);

        switch (tag.getReqId()) {
            case REQUEST_LIWUS:
                GiftDataAll giftDataAll = (GiftDataAll) data;
                giftDatas=new ArrayList<>();
                if(giftDataAll.getPresent()!=null && giftDataAll.getPresent().size()>0)
                    giftDatas.addAll(giftDataAll.getPresent());
                if(giftDataAll.getWeek()!=null && giftDataAll.getWeek().size()>0){
                    giftDatas.addAll(giftDataAll.getWeek());
                }
                if(giftDatas!=null && giftDatas.size()>0){
                    ((TextView) rootView.findViewById(R.id.tv_surplus)).setText("E币余额："+MyApplication.getInstance().e_money);
                    GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
                    gridview.setAdapter(new CommonAdapter<GiftData>(getContext(),giftDatas,R.layout.item_gift) {
                        @Override
                        public void convert(BaseViewHolder holder, GiftData itemData, int position, ViewGroup parent) {
                            if(!TextUtils.isEmpty(itemData.getWeek_id())){
                                holder.setImageByUrl(R.id.iv_img,itemData.getWeek_img(), null);
                                holder.setText(R.id.tv_cost,itemData.getWeek_price());
                                holder.setText(R.id.tv_name,itemData.getWeek_name());
                                holder.getView(R.id.iv_week).setVisibility(View.VISIBLE);
                            }else{
                                holder.setImageByUrl(R.id.iv_img,itemData.getImage(),null);
                                holder.setText(R.id.tv_cost,itemData.getCoin());
                                holder.setText(R.id.tv_name,itemData.getName());
                                holder.getView(R.id.iv_week).setVisibility(View.GONE);
                            }

                        }
                    });
                    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            GiftData giftData = giftDatas.get(position);
                            try {
                                if(!TextUtils.isEmpty(giftData.getWeek_id())){
                                    cost = Integer.valueOf(giftData.getWeek_price());
                                }else{
                                    cost = Integer.valueOf(giftData.getCoin());
                                }
                            } catch (Exception e) {
                                // TODO: handle exception
                            }
                            if(MyApplication.getInstance().e_money<cost){
                                new YesOrNoDialog(getContext(), new YesOrNoDialogEntity("您的E币余额不够，请及时充值", "我知道了", "立即充值"), new YesOrNoDialog.OnYesOrNoDialogClickListener() {
                                    @Override
                                    public void onYesOrNoDialogClick(YesOrNoDialog.YesOrNoType yesOrNoType) {
                                        switch (yesOrNoType) {
                                            case BtnOk:
                                                MyApplication.getInstance().gotoCharge();
                                                break;

                                            default:
                                                break;
                                        }
                                    }
                                }).show();
                            }else{
                                MyApplication.getInstance().e_money = MyApplication.getInstance().e_money-cost;
                                requestDashang(giftData.getId());
                            }
                        }
                    });
                }
                break;
            case REQUEST_DASANG:
                giftChangeListener.onSendGift(id);
                Toast.makeText(getContext(),"打赏成功",Toast.LENGTH_SHORT).show();
                ((TextView) rootView.findViewById(R.id.tv_surplus)).setText("E币余额："+MyApplication.getInstance().e_money);
                break;
            default:
                break;
        }
    }

    @Override
    public void onApiFailure(ReqTag tag, MamaHaoServerError error, AbstractRequest.MamaHaoError clientError) {
        common_error_page_progressBar.setVisibility(View.GONE);
        switch (tag.getReqId()) {
            case REQUEST_DASANG:
                MyApplication.getInstance().e_money = MyApplication.getInstance().e_money+cost;
                if(error!=null && !TextUtils.isEmpty(error.msg))
                    Toast.makeText(getContext(),error.msg,Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    public interface GiftChangeListener{
        void onSendGift(String id);
        void onDissmiss();
    }
}
